package com.chuangke.security.filter;

import java.io.IOException;
import java.util.stream.Collectors;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chuangke.common.exception.ChuangkeException;
import com.google.code.kaptcha.Constants;

import cn.hutool.core.util.StrUtil;

public class CaptchaFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		if ("/login".equals(request.getRequestURI())) {
			// 获取请求体中的JSON数据
			String requestBody = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
			JSONObject jsonObject = JSON.parseObject(requestBody);

			// 从JSON中获取验证码
			String inputCaptcha = jsonObject.getString("captcha");

			Object captcha = request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
			request.getSession().removeAttribute(Constants.KAPTCHA_SESSION_KEY);

			if (StrUtil.isBlank(inputCaptcha)) {
				throw new ChuangkeException("请输入验证码");
			}
			if (captcha == null) {
				throw new ChuangkeException("验证码已失效");
			}
			if (!captcha.equals(inputCaptcha)) {
				throw new ChuangkeException("验证码不正确");
			}
		}

		// 验证码正确，继续处理请求
		filterChain.doFilter(request, response);
	}
}